package com.example.demo_yunpan.controller;
import com.example.demo_yunpan.entity.user;
import com.example.demo_yunpan.service.UserService;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.List;
import com.example.demo_yunpan.config.*;

@RestController
@CrossOrigin(origins = "http://localhost:5173")
public class Usercontroller {
    @Autowired
    private UserService userService;
    @Autowired
    private SecurityConfig SecurityConfig;

    //private RedisTemplate<String, Object> redisTemplate;

    //private FileSystem fileSystem;

    //登录
    @PostMapping ("/login")
    public String Login(@RequestParam String userName, @RequestParam String userPass){

        //验证用户身份
        user u = userService.userLogin(userName,userPass);
        System.out.println(userName);
        if(u!=null){

            //登录成功，将用户头像从HDFS读取到Redis
            //String hdfsPath = u.getAvatarHdfs();
            /*try{
                FSDataInputStream in = fileSystem.open(new Path(hdfsPath));
                byte[] avatarBytes = IOUtils.toByteArray(in);
                in.close();
                //redisTemplate.opsForValue().set("avatar:" + u.getUserName(), avatarBytes);

                return "登录成功";
            }catch (IOException e){
                return "从HDFS读取用户头像失败: " + e.getMessage();
            }*/
            return "成功";
        }else{
            return "用户密码错误";
        }
    }

    //注册
    @PostMapping("/register")
    public String register(@RequestParam String userName, @RequestParam String userPass) throws IOException {
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        int sucess = 0;
        //判断数据是否合规
        if(userName == null || userName.trim().isEmpty()){
            return "请输入用户名";
        }
        else if(userPass == null || userPass.trim().isEmpty()){
            return "请输入密码";
        }else{
            userPass=passwordEncoder.encode(userPass);
             sucess = userService.userRegister(userName,userPass);
        }
        if(sucess == 1){
            return "注册成功";
        }else{
            return "注册失败";
        }
    }

    //查看个人信息查询
    @PostMapping("/userInfo")
    public ResponseEntity<?> checkUserInfo(@RequestParam(required = false) String userId){
        // 验证用户ID是否为空
        if (userId == null || userId.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }
        // 查询用户信息
        user u = userService.selectUserById(userId);
        if (u == null) {
            return ResponseEntity.badRequest().body("查询失败");
        }
        return ResponseEntity.ok(u);
    }

    //修改个人信息
    @PutMapping("/changeInfo/{id}")
    public ResponseEntity<?> updateUserInfo(@RequestBody user u,@PathVariable int id){

        //验证修改id是否为当前userId
        if(id != u.getUserId()){
            return ResponseEntity.badRequest().body("请求路径中的ID与用户对象中的ID不匹配");
        }
        //验证用户对象属性,根据需要可以添加更多验证
        if (u.getUserName() == null || u.getUserName().trim().isEmpty()) {
            return ResponseEntity.badRequest().body("用户名不能为空");
        }
        if (u.getUserPass() == null || u.getUserPass().trim().isEmpty()) {
            return ResponseEntity.badRequest().body("密码不能为空");
        }

        int result = userService.updateUser(u);
        if(result == 0){
            return ResponseEntity.badRequest().body("用户信息更新失败");
        }
        // 返回更新后的用户信息或成功消息
        return ResponseEntity.ok("用户信息更新成功");
    }



    //提供访问用户头像接口
    /*@GetMapping("/avatar/{username}")
    public ResponseEntity<byte[]> getAvatar(@PathVariable String username) {
        // 从Redis中获取Base64编码的头像
        String base64Avatar = (String) redisTemplate.opsForValue().get("avatar:" + username);
        if (base64Avatar != null) {
            return new ResponseEntity<>(base64Avatar.getBytes(StandardCharsets.UTF_8), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }*/
}
